﻿Imports knfUpdateDataLayer

Public Class EseguiCalcoloPerReporter

    Private _db As knfEntities

    Private nAnno As Integer
    Public Property Anno As Integer
        Get
            Return nAnno
        End Get
        Set(ByVal value As Integer)
            nAnno = value
        End Set
    End Property

    Private nReporter As String
    Public Property Reporter() As String
        Get
            Return nReporter
        End Get
        Set(ByVal value As String)
            nReporter = value
        End Set
    End Property

    Public Sub New(ByVal anno As Integer, ByVal reporter As String)
        nAnno = anno
        nReporter = reporter
        _db = New knfEntities()


    End Sub

    Public Sub Agisci(ByVal listaReporter As List(Of RawData), ByVal listaPartner As List(Of RawData))

        Dim aliasProduct As String = String.Empty

        For i As Integer = 0 To 1

            Select Case i
                Case 0
                    aliasProduct = "Glass Mineral Wool"

                Case 1
                    aliasProduct = "Rock Mineral Wool"

                Case 2
                    aliasProduct = "Wood Wool"

            End Select

            'genera per tons
            GeneraReportPerProductPerCountryPerAnnoScelto(aliasProduct, Reporter, "Ton",
                                                         nAnno, listaReporter, listaPartner)
            'genera per euro
            GeneraReportPerProductPerCountryPerAnnoScelto(aliasProduct, Reporter, "Euro",
                                                         nAnno, listaReporter, listaPartner)
        Next



    End Sub

    Private Sub GeneraReportPerProductPerCountryPerAnnoScelto(ByVal aliasProduct As String, _
                                     ByVal Country As String, _
                                     ByVal reportType As String,
                                     ByVal Anno As Integer,
                                     ByRef ListaReporterAnnoScelto As List(Of RawData),
                                     ByRef ListaPartnerAnnoScelto As List(Of RawData))



        ' considera i REPORTERS e i PARTNERS associati per prodotto

        Dim vpartners As New List(Of viewDistinctPartnersForReporters)
        vpartners = AssociaPartnersAReporterRivisto(Country, aliasProduct)

        If Not vpartners Is Nothing Then

            Dim vp As New List(Of String)
            For Each tmp In vpartners
                vp.Add(tmp.PARTNER_LAB)
            Next

            ''aggiungi entrambi i tipi di flows

            Dim flow As New List(Of String)

            flow.Add("IMPORT")
            flow.Add("EXPORT")

            For Each fitem In flow

                Dim ListaAnni As New List(Of Integer)
                ListaAnni.Add(Anno)

                For Each tmpYear As Integer In ListaAnni
                    FaiLaCosaGiusta(aliasProduct, Country, fitem, vp, reportType, tmpYear,
                                    ListaReporterAnnoScelto, ListaPartnerAnnoScelto)
                Next
            Next

        End If

    End Sub

    Public Function AssociaPartnersAReporterRivisto(ByVal Reporter As String, ByVal AliasProduct As String) As List(Of viewDistinctPartnersForReporters)

        Try

            Dim var2 = PartnersDistintiPerProdotto(AliasProduct, Reporter)


            If var2 Is Nothing Then

                Return PartnersDistintiPerProdottoCasoNullo(AliasProduct, Reporter)
            Else
                Return var2.ToList
            End If


        Catch ex As Exception
            Return Nothing
        End Try

    End Function

    Private Function PartnersDistintiPerProdotto(ByVal AliasProduct As String, ByVal Reporter As String) As List(Of viewDistinctPartnersForReporters)

        Dim tmpList As New List(Of viewDistinctPartnersForReporters)
        Dim tmpListPartner As New List(Of viewDistinctPartnersForReporters)

        Try

            If AliasProduct = "Glass Mineral Wool" Then
                Dim var = (From p In _db.viewDistinctPartnersForReporters Where p.REPORTER_LAB.Trim = Reporter.Trim And p.PRODUCT > 70000000 Order By p.PARTNER_LAB Select p)
                tmpList.AddRange(var)
            ElseIf AliasProduct = "Rock Mineral Wool" Then
                Dim var = (From p In _db.viewDistinctPartnersForReporters Where p.REPORTER_LAB.Trim = Reporter.Trim And p.PRODUCT = 68061000 Order By p.PARTNER_LAB Select p)
                tmpList.AddRange(var)
            End If

            If tmpList.Count > 0 Then

                Dim var2 = (From p In tmpList Order By p.PARTNER_LAB Select p.PARTNER_LAB).Distinct

                For Each tmpPartner As String In var2
                    Dim newPartner As New viewDistinctPartnersForReporters
                    newPartner.PARTNER_LAB = tmpPartner
                    tmpListPartner.Add(newPartner)
                Next

                Return tmpListPartner

            Else

                Return Nothing

            End If


        Catch ex As Exception
            Return Nothing
        End Try

    End Function

    Private Function PartnersDistintiPerProdottoCasoNullo(ByVal AliasProduct As String, ByVal Reporter As String) As List(Of viewDistinctPartnersForReporters)

        Dim tmpList As New List(Of viewDistinctPartnersForReporters)
        Dim tmpListPartner As New List(Of viewDistinctPartnersForReporters)

        Try

            If AliasProduct = "Glass Mineral Wool" Then
                Dim var = (From p In _db.viewDistinctPartnersForReporters Where p.PARTNER_LAB.Trim = Reporter.Trim And p.PRODUCT > 70000000 Order By p.REPORTER_LAB Select p)
                tmpList.AddRange(var)
            ElseIf AliasProduct = "Rock Mineral Wool" Then
                Dim var = (From p In _db.viewDistinctPartnersForReporters Where p.PARTNER_LAB.Trim = Reporter.Trim And p.PRODUCT = 68061000 Order By p.REPORTER_LAB Select p)
                tmpList.AddRange(var)
            End If

            If tmpList.Count > 0 Then

                Dim var2 = (From p In tmpList Order By p.REPORTER_LAB Select p.REPORTER_LAB).Distinct

                For Each tmpPartner As String In var2
                    Dim newPartner As New viewDistinctPartnersForReporters
                    newPartner.PARTNER_LAB = tmpPartner
                    tmpListPartner.Add(newPartner)
                Next

                Return tmpListPartner

            Else

                Return Nothing

            End If

        Catch ex As Exception
            Return Nothing
        End Try

    End Function

    Private Sub FaiLaCosaGiusta(ByVal kAliasProduct As String,
            ByVal kReporter As String, _
            ByVal kFlux As String,
            ByVal kPartners As List(Of String), _
            ByVal kKindOfReport As String, _
            ByVal kAnno As Integer,
            ByRef ListaReporterAnnoScelto As List(Of RawData),
            ByRef ListaPartnerAnnoScelto As List(Of RawData))


        For Each tmpPartner As String In kPartners

            Dim TotaleAllYear As Decimal = 0
            Dim TotaleAllYearMediato As Decimal = 0

            For indicemese = 1 To 12

                Dim partialValueMensile As Decimal = 0
                Dim partialValueMensileMediato As Decimal = 0
                Dim indiceMeseStringa As String = ConvertiInteroInMese(indicemese)

                partialValueMensile = DammiValoreMeseRiveduto(kReporter, tmpPartner,
                                               kFlux, kAnno.ToString, indiceMeseStringa, False,
                                               kKindOfReport, ListaReporterAnnoScelto, ListaPartnerAnnoScelto, kAliasProduct)

                TotaleAllYear += partialValueMensile


                partialValueMensileMediato = EstraiMedia(partialValueMensile, tmpPartner, kFlux, kAnno, indiceMeseStringa,
                                                         kKindOfReport, ListaPartnerAnnoScelto, kAliasProduct)

                TotaleAllYearMediato += partialValueMensileMediato

            Next

            If TotaleAllYear > 0 Then
                AggiungiSingoloTotaleATabella(kReporter, False, kFlux, kKindOfReport, tmpPartner, kAliasProduct, TotaleAllYear, kAnno)
            End If

            If TotaleAllYearMediato > 0 Then
                AggiungiSingoloTotaleATabella(kReporter, True, kFlux, kKindOfReport, tmpPartner, kAliasProduct, TotaleAllYearMediato, kAnno)
            End If

        Next

    End Sub

    Private Sub AggiungiSingoloTotaleATabella(ByVal Reporter As String, ByVal isAveraged As Boolean,
                                          ByVal Flux As String, ByVal Indicator As String,
                                          ByVal Partner As String, ByVal Product As String,
                                          ByVal Total As Decimal, ByVal Anno As Integer)



        Dim mTotal As New Tabella_Totali
        mTotal.Reporter = Reporter
        mTotal.Averaged = isAveraged
        mTotal.Flow = Flux
        mTotal.Indicator = Indicator
        mTotal.Partner = Partner
        mTotal.Product = Product
        mTotal.Total = Total
        mTotal.Year = Anno

        _db.Configuration.AutoDetectChangesEnabled = False
        _db.Tabella_Totali.Add(mTotal)
        _db.SaveChanges()



    End Sub

    Private Function ConvertiInteroInMese(ByVal indice As Integer) As String

        Select Case indice

            Case 1
                Return "Jan"
            Case 2
                Return "Feb"
            Case 3
                Return "Mar"
            Case 4
                Return "Apr"
            Case 5
                Return "May"
            Case 6
                Return "Jun"
            Case 7
                Return "Jul"
            Case 8
                Return "Aug"
            Case 9
                Return "Sep"
            Case 10
                Return "Oct"
            Case 11
                Return "Nov"
            Case 12
                Return "Dec"

        End Select

        Return String.Empty

    End Function

    Private Function DammiValoreMeseRiveduto(ByVal kReporter As String,
                        ByVal Partner As String,
                        ByVal kFlux As String,
                        ByVal Anno As String,
                        ByVal Mese As String,
                        ByVal EseguiMediaBool As Boolean,
                        ByVal kKindOfReport As String,
                        ByRef ListaReporterAnnoScelto As List(Of RawData),
                        ByRef ListaPartnerAnnoScelto As List(Of RawData),
                        ByVal AliasProduct As String) As Decimal


        Dim var = SommaRawDataPerMonthReporterRiveduto(kReporter, Partner,
                                       kFlux, Anno, Mese, EseguiMediaBool,
                                       ListaReporterAnnoScelto, ListaPartnerAnnoScelto, AliasProduct)

        Dim partialValue As Decimal = 0
        If var IsNot Nothing Then
            Select Case kKindOfReport
                Case "Ton"
                    partialValue = var.Tonnellate
                Case "Euro"
                    partialValue = var.TotaleEuro
            End Select
        Else
            partialValue = 0
        End If

        Return partialValue

    End Function

    Private Function SommaRawDataPerMonthReporterRiveduto(ByVal Reporter As String, _
              ByVal Partner As String, _
              ByVal Flux As String, ByVal Year As String, _
              ByVal Month As String, _
              ByVal EseguiMediaBool As Boolean, _
              ByRef ListaReporterAnnoScelto As List(Of RawData),
              ByRef ListaPartnerAnnoScelto As List(Of RawData),
              ByVal AliasProduct As String) As RawData

        Try

            Dim ListaTemporanea As New List(Of RawData)
            Dim tonn As Decimal = 0
            Dim price As Decimal = 0

            Dim myFlux As String
            Dim FlussoNumerico As Integer = 0

            If Flux = "IMPORT" Then
                FlussoNumerico = 1
            ElseIf Flux = "EXPORT" Then
                FlussoNumerico = 2
            End If

            ' Dim idCheck As Integer = 0
            Dim myPeriod As String = ConvertiStringaMese(Month, Year)

            Dim tmpRawList As New List(Of RawData)
            tmpRawList = EstraiRawDataReporterRiveduto(Partner, Flux, myPeriod, ListaReporterAnnoScelto, AliasProduct)

            If tmpRawList.Count <= 0 Then

                ' Devo invertire i ruoli

                If Flux = "IMPORT" Then
                    myFlux = "EXPORT"
                ElseIf Flux = "EXPORT" Then
                    myFlux = "IMPORT"
                Else
                    myFlux = String.Empty
                End If

                tmpRawList = EstraiRawDataPartnerRiveduto(Partner, myFlux, myPeriod, ListaPartnerAnnoScelto, AliasProduct)


            End If

            If tmpRawList.Count > 0 Then

                For Each tmpRaw As RawData In tmpRawList

                    If tmpRaw.INDICATORS_LAB = "QUANTITY_IN_100KG" Then
                        tonn += tmpRaw.INDICATOR_VALUE * 0.1
                    ElseIf tmpRaw.INDICATORS_LAB = "VALUE_IN_EUROS" Then
                        price += tmpRaw.INDICATOR_VALUE
                    End If

                Next

                Dim nuovoRawData As New RawData
                With nuovoRawData
                    .Tonnellate = tonn
                    If tonn <> 0 Then
                        .TotaleEuro = price / tonn
                    Else
                        .TotaleEuro = 0
                    End If

                    .FLOW = FlussoNumerico
                    .FLOW_LAB = Flux
                    .INDICATOR_VALUE = 0
                    .INDICATORS = 0
                    .INDICATORS_LAB = 0
                    .PARTNER_LAB = Partner
                    .PERIOD = 0
                    .PERIOD_LAB = myPeriod
                    .PRODUCT_LAB = ""
                    .REPORTER_LAB = Reporter

                    Dim tmpString As String
                    Dim tmpString2 As String

                    tmpString = tmpRawList(0).PERIOD
                    tmpString2 = Mid(tmpString, 1, 4)
                    .Year = CType(tmpString2, Integer)
                    .Month = Mid(tmpString, 5, 2)

                End With

                If EseguiMediaBool = True Then
                    Dim tmpList As New List(Of RawData)
                    tmpList.Add(nuovoRawData)
                    tmpList = CalcolaMediaRiveduto(tmpList, ListaPartnerAnnoScelto, AliasProduct)
                    Return tmpList(0)

                Else

                    Return nuovoRawData

                End If

            End If

        Catch ex As Exception
            Return Nothing
        End Try


    End Function

    Private Function ConvertiStringaMese(ByVal InString As String, ByVal StringaAnno As String) As String

        Select Case InString
            Case "Jan"
                Return StringaAnno + "01"
            Case "Feb"
                Return StringaAnno + "02"
            Case "Mar"
                Return StringaAnno + "03"
            Case "Apr"
                Return StringaAnno + "04"
            Case "May"
                Return StringaAnno + "05"
            Case "Jun"
                Return StringaAnno + "06"
            Case "Jul"
                Return StringaAnno + "07"
            Case "Aug"
                Return StringaAnno + "08"
            Case "Sep"
                Return StringaAnno + "09"
            Case "Oct"
                Return StringaAnno + "10"
            Case "Nov"
                Return StringaAnno + "11"
            Case "Dec"
                Return StringaAnno + "12"
        End Select

        Return String.Empty

    End Function

    Private Function EstraiRawDataReporterRiveduto( _
               ByVal Partner As String, _
               ByVal Flux As String, _
               ByVal Period As Integer,
               ByRef ListaReporterAnnoScelto As List(Of RawData),
               ByVal AliasProduct As String) As List(Of RawData)

        Dim gPartner As New List(Of RawData)


        Try


            If AliasProduct = "Glass Mineral Wool" Then

                Dim varGigi = From p In ListaReporterAnnoScelto Where _
                          p.PARTNER_LAB.Trim = Partner.Trim And _
                          p.FLOW_LAB.Trim = Flux.Trim And _
                          p.PRODUCT > 70000000 And _
                          p.PERIOD = Period _
                          Select p

                gPartner = varGigi.ToList



            ElseIf AliasProduct = "Rock Mineral Wool" Then


                Dim varGigi = From p In ListaReporterAnnoScelto Where _
                          p.PARTNER_LAB.Trim = Partner.Trim And _
                          p.FLOW_LAB.Trim = Flux.Trim And _
                          p.PRODUCT = 68061000 And _
                          p.PERIOD = Period _
                          Select p

                gPartner = varGigi.ToList

            End If

            Return gPartner

        Catch ex As Exception
            Return Nothing
        End Try


    End Function

    Private Function EstraiRawDataPartnerRiveduto(ByVal Reporter As String, _
                 ByVal Flux As String, _
                 ByVal Period As Integer, _
                 ByRef ListaPartnerAnnoScelto As List(Of RawData),
                 ByVal AliasProduct As String) As List(Of RawData)


        Dim gPartner As New List(Of RawData)


        Try

            If AliasProduct = "Glass Mineral Wool" Then

                Dim varGogo = From p In ListaPartnerAnnoScelto Where _
                          p.REPORTER_LAB.Trim = Reporter.Trim And _
                          p.FLOW_LAB.Trim = Flux.Trim And _
                          p.PRODUCT > 70000000 And _
                          p.PERIOD = Period _
                          Select p

                gPartner = varGogo.ToList

            ElseIf AliasProduct = "Rock Mineral Wool" Then

                Dim varGogo = From p In ListaPartnerAnnoScelto Where _
                        p.REPORTER_LAB.Trim = Reporter.Trim And _
                        p.FLOW_LAB.Trim = Flux.Trim And _
                        p.PRODUCT = 68061000 And _
                        p.PERIOD = Period _
                        Select p

                gPartner = varGogo.ToList


            End If

            Return gPartner

        Catch ex As Exception
            Return Nothing
        End Try


    End Function

    Private Function CalcolaMediaRiveduto(ByVal inList As List(Of RawData),
                                      ByRef ListaPartnerAnnoScelto As List(Of RawData),
                                      ByVal AliasProduct As String) As List(Of RawData)

        Try

            For Each tmpRaw As RawData In inList

                Dim localList As New List(Of RawData)
                Dim tmpFlux As String
                Dim tonn As Decimal
                Dim price As Decimal

                If tmpRaw.FLOW_LAB = "EXPORT" Then
                    tmpFlux = "IMPORT"
                ElseIf tmpRaw.FLOW_LAB = "IMPORT" Then
                    tmpFlux = "EXPORT"
                Else
                    tmpFlux = String.Empty
                End If

                localList = EstraiRawDataPartnerRiveduto(tmpRaw.PARTNER_LAB, _
                                           tmpFlux, tmpRaw.PERIOD, ListaPartnerAnnoScelto, AliasProduct)

                For Each tmpList In localList

                    If tmpList.INDICATORS_LAB = "QUANTITY_IN_100KG" Then
                        tonn = tmpList.INDICATOR_VALUE * 0.1
                    ElseIf tmpList.INDICATORS_LAB = "VALUE_IN_EUROS" Then
                        price = tmpList.INDICATOR_VALUE
                    End If
                Next

                Dim nuoveTonn As Decimal
                Dim nuovoPrezzo As Decimal
                If tonn <> 0 Then
                    nuoveTonn = (tmpRaw.Tonnellate + tonn) / 2
                    nuovoPrezzo = (tmpRaw.TotaleEuro + (price / tonn)) / 2
                Else
                    nuoveTonn = tmpRaw.Tonnellate
                    nuovoPrezzo = tmpRaw.TotaleEuro
                End If

                tmpRaw.Tonnellate = System.Math.Round(nuoveTonn, 0)
                tmpRaw.TotaleEuro = System.Math.Round(nuovoPrezzo, 0)

            Next

            Return inList

        Catch ex As Exception

            Return inList

        End Try

    End Function

    Private Function EstraiMedia(ByVal OriginalValue As Decimal,
                        ByVal Partner As String,
                        ByVal kFlux As String,
                        ByVal Anno As String,
                        ByVal Mese As String,
                        ByVal kKindOfReport As String,
                        ByRef ListaPartnerAnnoScelto As List(Of RawData),
                        ByVal AliasProduct As String) As Decimal

        Dim localList As New List(Of RawData)

        Dim tonn As Decimal = 0
        Dim price As Decimal = 0
        Dim tmpFlux As String = String.Empty
        Dim Period As String = ConvertiStringaMese(Mese, Anno)

        If kFlux = "EXPORT" Then
            tmpFlux = "IMPORT"
        ElseIf kFlux = "IMPORT" Then
            tmpFlux = "EXPORT"
        End If


        localList = EstraiRawDataPartnerRiveduto(Partner, _
                                   tmpFlux, Period, ListaPartnerAnnoScelto, AliasProduct)

        If localList.Count > 0 Then

            For Each tmpList In localList

                If tmpList.INDICATORS_LAB = "QUANTITY_IN_100KG" Then
                    tonn += tmpList.INDICATOR_VALUE * 0.1
                ElseIf tmpList.INDICATORS_LAB = "VALUE_IN_EUROS" Then
                    price += tmpList.INDICATOR_VALUE
                End If
            Next

            If kKindOfReport = "Ton" Then

                Dim nuoveTonn As Decimal = 0
                nuoveTonn = (OriginalValue + tonn) / 2
                Return nuoveTonn
            ElseIf kKindOfReport = "Euro" Then

                Dim nuovoPrezzo As Decimal = 0

                If tonn <> 0 Then
                    nuovoPrezzo = (OriginalValue + (price / tonn)) / 2
                Else
                    nuovoPrezzo = OriginalValue
                End If

                Return nuovoPrezzo

            Else

                Return OriginalValue

            End If

        Else

            Return OriginalValue

        End If


    End Function

End Class
